const {Tray, Menu} = require('electron');
const path = require('path');
const {logger} = require('ee-core/log');
const Electron = require('ee-core/electron');
const CoreWindow = require('ee-core/electron/window');
const {getConfig} = require('ee-core/config');
// const EE = require('ee-core/ee');
const {getBaseDir} = require('ee-core/ps');

/**
 * 托盘插件
 * @class
 */
class TrayAddon {

    constructor() {
        this.tray = null;
    }

    /**
     * 创建托盘
     */
    create() {
        const {addons} = getConfig();
        const cfg = addons.tray;
        if (!cfg.enable) {
            Electron.setCloseAndQuit(true);
            return;
        } else {
            Electron.setCloseAndQuit(false);
        }
        const mainWindow = CoreWindow.getMainWindow();

        // 托盘图标
        let iconPath = path.join(getBaseDir(), cfg.icon);

        // 托盘菜单功能列表
        let trayMenuTemplate = [
            {
                label: '显示',
                click: function () {
                    mainWindow.show();
                }
            },
            {
                label: '隐藏',
                click: function () {
                    mainWindow.hide();
                }
            },
            {
                label:'开发者模式',
                click:function(){
                    mainWindow.webContents.openDevTools({ mode: 'detach' });
                }
            },
            {
                label: '退出',
                click: function () {
                    // CoreApp.appQuit();
                    Electron.setCloseAndQuit(true);
                    mainWindow.close();
                }
            }
        ]

        // 点击关闭，最小化到托盘
        mainWindow.on('close', (event) => {
            logger.info(`[Electron.getCloseAndQuit()]:${Electron.getCloseAndQuit()}`);
            if (Electron.getCloseAndQuit() === true) {
                return;
            }
            mainWindow.hide();
            event.preventDefault();
        });

        // 实例化托盘
        this.tray = new Tray(iconPath);
        this.tray.setToolTip(cfg.title);
        const contextMenu = Menu.buildFromTemplate(trayMenuTemplate);
        this.tray.setContextMenu(contextMenu);
        // 左键单击的时候能够显示主窗口
        this.tray.on('click', () => {
            mainWindow.show()
        })
    }
}

TrayAddon.toString = () => '[class TrayAddon]';
module.exports = TrayAddon;